/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.controller;

import es.silenus.detecta.Constants;

import es.silenus.detecta.dao.Page;
import es.silenus.detecta.dao.ProvinceDAO;

import es.silenus.detecta.model.Organization;
import es.silenus.detecta.model.Province;

import es.silenus.detecta.service.OrganizationService;
import es.silenus.detecta.service.AlfrescoService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Organization controller.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 02-abr-2009 10:25:50
 */
public class OrganizationController extends BaseController {
	/**
	 * The organization DAO.
	 */
	private OrganizationService organizationService;

	/**
	 * The province DAO.
	 */
	private ProvinceDAO provinceDAO;

	/**
	 * The alfresco service.
 	 */
	private AlfrescoService alfrescoService;

	/**
	 * Sets the organization service.
	 *
	 * @param organizationService the organization service.
	 */
	public void setOrganizationService(final OrganizationService organizationService) {
		this.organizationService = organizationService;
	}

	/**
	 * Sets the province DAO.
	 *
	 * @param provinceDAO the province DAO.
	 */
	public void setProvinceDAO(final ProvinceDAO provinceDAO) {
		this.provinceDAO = provinceDAO;
	}

	/**
	 * Sets the alfresco service.
	 *
	 * @param alfrescoService the alfresco service.
	 */
	public void setAlfrescoService(final AlfrescoService alfrescoService) {
		this.alfrescoService = alfrescoService;
	}

	/**
	 * Retrieves the list of organizations.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the list of organizations.
	 */
	public String getOrganizations(final HttpServletRequest request, final HttpServletResponse response) {
		String query = request.getParameter("query");

		List<Organization> result;

		if((query != null) && (query.length() > 0)) {
			Map<String, Object> sample = new HashMap<String, Object>();

			sample.put("name", query);
			result = organizationService.findOrganizationsByExample(sample);
		} else {
			result = organizationService.findAllOrganizations();
		}

		request.setAttribute("result", result);

		return "secure/admin/organizations";
	}

	/**
	 * Updates an organization.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String updateOrganization(final HttpServletRequest request, final HttpServletResponse response) {
		String id = request.getParameter("id");

		int orgId = (id != null) ? Integer.parseInt(id) : 0;

		Organization organization;

		if(orgId > 0) {
			organization = organizationService.findOrganizationById(orgId);
		} else {
			organization = new Organization();
		}

		String temp = request.getParameter("name");

		if(temp != null) {
			organization.setName(temp);

			Organization otherOrganization = organizationService.findOrganizationByName(temp);

			if((otherOrganization != null) && (otherOrganization.getId() != orgId)) {
				request.setAttribute(Constants.ERRORS, "organization.name.duplicated");

				return "secure/admin/organization-update-error";
			}
		}

		// Remove before add
		organization.getProvinces().clear();

		temp = request.getParameter("provinces");

		if((temp != null) && (temp.length() > 0)) {
			String[] provinceIds = temp.split(",");
			List<Province> provinces = provinceDAO.findByIds(provinceIds);

			organization.getProvinces().addAll(provinces);
		}

		if(orgId > 0) {
			organizationService.updateOrganization(organization);
		} else {
			organizationService.createOrganization(organization);
		}

		request.setAttribute("organization", organization);

		return "secure/admin/organization-updated";
	}

	/**
	 * Updates an organization.
	 *
	 * @param request the request.
	 * @param response the response.
	 *
	 * @return the view name.
	 */
	public String findOrganizations(final HttpServletRequest request, final HttpServletResponse response) {
		Map<String, Object> sample = new HashMap<String, Object>();
		String temp = request.getParameter("id");

		if(temp != null) {
			sample.put("id", temp);
		}

		temp = request.getParameter("name");

		if(temp != null) {
			sample.put("name", temp);
		}

		temp = request.getParameter("provinces");

		if((temp != null) && (temp.length() > 0)) {
			String[] provinces = temp.split(",");

			sample.put("provinces", provinces);
		}

		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		String[] sortFields = request.getParameterValues("sort");
		String[] sortDirections = request.getParameterValues("dir");

		Page<Organization> page = organizationService.findOrganizationsByExample(
				sample, start, limit, sortFields, sortDirections);

		request.setAttribute("page", page);

		return "secure/admin/organization-search";
	}


	/**
	 * Checks the organizations.
	 *
	 * @param request the request.
	 * @param response the response.
	 * @return the view name.
	 */
	public String checkOrganizations(final HttpServletRequest request, final HttpServletResponse response) {

		final List<Organization> organizations = organizationService.findAllOrganizations();

		// Check organizations in alfresco, their folders also (LDAP can also be updated)
		String organizationName;
		Organization checkedOrganization;
		for(final Organization organization: organizations) {

			organizationName = organization.getName();

			checkedOrganization = organizationService.findOrganizationByName(organizationName);

			// Create non-existent alfresco groups
			if(!alfrescoService.groupExists(organizationName)) {

				alfrescoService.createGroup(organizationName);

			}

			// Check alfresco group folders.
			alfrescoService.checkOrganizationFolder(organizationName);

		}

		return JSON_SUCCESS_VIEW;
	}
}
